<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="userName"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number.trim="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addBtn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
        v-show="user.length !== 0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in user" :key="index">
          <td>{{index + 1}}</td>
          <td>{{item.userName}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="delBtn(index)">删除</button>
            <button @click="editBtn(item, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      userName: '',
      age: '',
      sex: '',
      user: [],
      falg: true,
      arrIndex: 0
    }
  },
  methods: {
    addBtn () {
      if (this.falg === true) {
        if (this.userName === '' || this.age === '' || this.sex === '') {
        return alert('输入不能为空')
      }
        this.user.push(
          {
            userName: this.userName,
            age: this.age,
            sex: this.sex
          }
        )
      } else {
        console.log(this.arrIndex)
        this.user.splice(this.arrIndex, 1 ,{
          userName: this.userName,
          age: this.age,
          sex: this.sex
        })
      }
        this.userName = '',
        this.age = '',
        this.sex = ''
      },
    delBtn (index) {
      this.user.splice(index, 1)
    },
    editBtn (item, index) {
      console.log(item)
      this.arrIndex = index
      this.userName = item.userName
      this.age = item.age
      this.sex = item.sex
      this.falg = false
    }
    },
}

</script>